<template>
    <el-row style="justify-content: center;align-items:center;height: 5vh;padding-left: 2%;padding-right: 3%">
        <el-col :span="8">
            <el-radio-group v-model="radio" size="large" @change="changeRadio">
                <el-radio-button label="扫码入库" />
                <el-radio-button label="进货单" />
            </el-radio-group>
        </el-col>
        <el-col :span="8" style="text-align: right;padding-right: 2%">
            <el-button v-if="radio==='扫码入库'" size="large" round style="width: 150px;" @click="checkPurchase">加入进货单</el-button>
        </el-col>
        <el-col :span="8" style="text-align: center">
            <el-autocomplete
                v-model="searchValue"
                placeholder="输入名称或条码"
                :prefix-icon="Search"
                style="width: 20vw"
                size="large"
                :trigger-on-focus="false"
                :fetch-suggestions="querySearch"
                clearable
                @select="handleSearchSelect"
            >
                <template #default="{ item }">
                    <div >
                        <el-text>{{ item.goodsName }}</el-text>
                    </div>
                    <div >
                        <el-text size="small">{{ item.code }}</el-text>
                    </div>
                </template>
            </el-autocomplete>
        </el-col>
    </el-row>
    <div style="margin-top: 2vh">
        <el-table :data="tableData(curTableData)"
                  height="72vh"
                  style="width: 100%;"
                  :header-cell-style="{ background: '#f6f6f6',  }"
                  @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection"  />
            <el-table-column label="商品名/条码" width="300">
                <template #default="scope">
                    <el-row>
                        <el-col span="24" style="padding-left: 5%;">
                            <el-row style="max-width: 145px"><el-text>{{ scope.row.goodsName }}</el-text></el-row>
                            <el-row><el-text>{{ scope.row.code }}</el-text></el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column prop="cost" label="成本价" />
            <el-table-column prop="inventory" label="库存"/>
            <el-table-column prop="warn" label="预警库存"/>
            <el-table-column label="预进货数">
                <template #default="scope">
                    <el-input-number v-model="scope.row.num" :min="1"  style="width: 60%"/>
                </template>
            </el-table-column>
        </el-table>

        <div style="justify-content: center;align-items:center;height: 70px; background-color: rgba(255,255,255,0.72);boxShadow:1px 0px 1px #a6a6a6;z-index: 999;display: flex;padding: 5px 25px 5px 25px;">
          <el-row style="flex: 15;" justify="start">
            <div style="text-align: center;margin: 10px 20px 10px 10px">
              <div>
                <el-text size="large">入库种类： {{getTotalAndNum().num}}种 &nbsp;&nbsp;&nbsp; 入库金额： {{(getTotalAndNum().total).toFixed(2)}}元</el-text>
              </div>
            </div>
            <div style="text-align: center;margin: 10px 20px 10px 10px">
              <el-button type="danger" round @click="delMgr">
                移除选中
              </el-button>
            </div>
            <div style="text-align: center;margin: 10px 20px 10px 10px">
              <el-button type="primary" round @click="addGoodsNum" style="width: 150px;">
                一键入库
              </el-button>
            </div>
          </el-row>
          <div style="flex: 9;" >
                <el-pagination
                        v-model:current-page="currentPage"
                        v-model:page-size="pageSize"
                        :background="true"
                        layout="->,prev, pager, next, jumper"
                        :total="store.warnInventory.length"
                        @current-change="handleCurrentChange"
                />
            </div>
        </div>
    </div>
    <el-dialog v-model="showCheck" title="以下商品进货后仍属于预警库存，是否继续？" width="40%" center>
        <el-row justify="center">
            <el-table :data="purchaseTemp"
                      height="50vh"
                      style="width: 100%;"
                      :header-cell-style="{ 'text-align': 'center' }"
                      :cell-style="{ textAlign: 'center' }"
            >
                <el-table-column label="商品名/条码" width="200">
                    <template #default="scope">
                        <el-row>
                            <el-col span="24" style="padding-left: 5%;">
                                <el-row style="max-width: 145px"><el-text>{{ scope.row.goodsName }}</el-text></el-row>
                                <el-row><el-text>{{ scope.row.code }}</el-text></el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column prop="inventory" label="库存" />
                <el-table-column prop="warn" label="预警库存" />
                <el-table-column prop="num" label="进货数" />
            </el-table>

        </el-row>
        <template #footer>
      <span style="text-align: center">
        <el-button  @click="showCheck=false">
          否
        </el-button>
        <el-button  @click="inPurchase">
          是
        </el-button>
      </span>
        </template>
    </el-dialog>
  <el-dialog v-model="showAddNew" title="新增商品"  width="30%" center>
    <el-form :model="goodsStore" :rules="rules" ref="dom" label-width="120px">
      <el-form-item label="商品条码" prop="code">
        <el-input v-model="goodsStore.code" style=" max-width: 250px;"/>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="goodsStore.goodsName" style=" max-width: 250px;"/>
      </el-form-item>
      <el-form-item label="零售价" prop="price">
        <el-input v-model="goodsStore.price" style=" max-width: 100px;"/>
        <el-button style="margin-left: 5%" type="primary" plain @click="getSuggestedPrice">建议价</el-button>
      </el-form-item>
      <el-form-item label="成本价" >
        <el-input v-model="goodsStore.cost" style=" max-width: 100px;"/>
      </el-form-item>
      <el-form-item label="初始库存" >
        <el-input v-model="goodsStore.inventory" style=" max-width: 100px;"/>
      </el-form-item>
      <el-form-item label="自定义库存预警" >
        <el-input v-model="goodsStore.warn" style=" max-width: 100px;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addGoodsShow = false">取消</el-button>
        <el-button type="primary" @click="submit(dom)">
          新增
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {store} from "@/store";
import {onMounted, reactive, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request";
import {Search} from "@element-plus/icons-vue";

const currentPage = ref(1)
const pageSize = ref(30)
const multipleSelection=ref([])
let showCheck=ref(false)
const purchaseTempAll=ref([])
let purchaseTemp=[]
const searchValue=ref("")
const radio=ref("扫码入库")
let goodsPurchase=ref({})
let curTableData=ref([])
let showAddNew=ref(false)

onMounted(()=>{
    request.get("/goods/get/goodsPurchase/"+store.getLocalCurrentStoreMain().storeId+"?isDone=0").then(res=>{
        goodsPurchase.value=res.data[0]
    })
    curTableData.value=store.state.waiting
  watchScanGun()
})
const tableData = (list) => {
    return list.filter(
        (item, index) =>
            index < currentPage.value * pageSize.value &&
            index >= pageSize.value * (currentPage.value - 1)
    );
};
const handleCurrentChange = (e) => {
    currentPage.value = e;
};
const handleSelectionChange = (val) => {
    multipleSelection.value = val
  console.log(multipleSelection.value)
}
const checkPurchase = () => {
    if (multipleSelection.value.length===0){
        ElMessage({
            message: '未选中商品',
            type: 'warning',
        })
    }else {
        purchaseTempAll.value=multipleSelection.value.filter((p)=>{
            if (p.num===undefined)
                p.num=1
            return true
        })
        const temp=multipleSelection.value.filter((p)=>{
            if (p.num===undefined)
                p.num=1
            return p.num+p.inventory<=p.warn
        })
        if (temp.length!==0){
            purchaseTemp=temp
            showCheck.value=true
        }else
            inPurchase()
    }

}
const inPurchase = () => {
    if (showCheck.value===true)
        showCheck.value=false
    request.get("/goods/get/goodsPurchase/"+store.getLocalCurrentStoreMain().storeId+"?isDone=0").then(res=>{
        if (res.data.length===0){
            let goodsPurchase={
                name:Date.now(),
                storeId:store.getLocalCurrentStoreMain().storeId,
                orderDetailObject:purchaseTempAll.value,
            }

            request.post("/goods/add/goodsPurchase",goodsPurchase).then(res=>{
                ElMessage({
                    message: '已新增进货单',
                    type: 'success',
                })
                delMultipleSelectionScan(false)
                request.get("/goods/get/goodsPurchase/"+store.getLocalCurrentStoreMain().storeId+"?isDone=0").then(res=>{
                    goodsPurchase.value=res.data[0]
                })
            })
        }else {
            for (let item in purchaseTempAll.value){
                if (res.data[0].orderDetailObject.filter((p)=>{return p.code.indexOf(purchaseTempAll.value[item].code) !==-1}).length!==0){
                    res.data[0].orderDetailObject[res.data[0].orderDetailObject.indexOf(res.data[0].orderDetailObject.filter((p)=>{
                        return p.code.indexOf(purchaseTempAll.value[item].code) !==-1})[0])]=purchaseTempAll.value[item]
                }else {
                    res.data[0].orderDetailObject.push(purchaseTempAll.value[item])
                }
            }
            request.post("/goods/update/goodsPurchase",res.data[0]).then(res=>{
                ElMessage({
                    message: '已将选中商品加入进货单',
                    type: 'success',
                })
                delMultipleSelectionScan(false)
                request.get("/goods/get/goodsPurchase/"+store.getLocalCurrentStoreMain().storeId+"?isDone=0").then(res=>{
                    goodsPurchase.value=res.data[0]
                })
            })
        }
    })
}
const querySearch = (queryString, cb) => {

    const results = queryString
        ? store.goodsStoreInfoList.filter((p)=>{
            return p.goodsName.indexOf(queryString) !==-1 || p.code.indexOf(queryString) !==-1
        })
        : store.goodsStoreInfoList
    // call callback function to return suggestions
    cb(results)
}

const handleSearchSelect = (item) => {
    onAddItem(item)
}
const onAddItem = (goodsInfo) => {

    if (curTableData.value.filter((p)=>{
        return p.code.indexOf(goodsInfo.code) !==-1
    }).length!==0){
        curTableData.value.filter((p)=>{
            curTableData.value[p.code.indexOf(goodsInfo.code)].num+=1
        })
    }else {
        goodsInfo.num=1
        curTableData.value.push(goodsInfo)
    }
}
const changeRadio = () => {
    curTableData.value=radio.value==='扫码入库'?store.state.waiting:goodsPurchase.value.orderDetailObject
}
const delMultipleSelectionScan = (isAll) => {
  if (isAll){
    curTableData.value=[]

  }else {
    for (let item in multipleSelection.value){
      curTableData.value=curTableData.value.filter(p=>{
        return p.code!==multipleSelection.value[item].code
      })

    }
  }

  store.state.waiting=curTableData.value
}
const delMultipleSelectionPurchase= () => {
    for (let item in multipleSelection.value){
      curTableData.value=curTableData.value.filter(p=>{
        return p.code!==multipleSelection.value[item].code
      })
    }
  // goodsPurchase.value.orderDetailObject=curTableData.value
  // request.post("/goods/update/goodsPurchase",goodsPurchase.value)

}
const delMgr = () => {
  if (radio.value==='扫码入库')
    delMultipleSelectionScan(false)
  else
    delMultipleSelectionPurchase()
}
const watchScanGun = () => {
  // 监听按键
  let code = '';
  let lastTime, nextTime; // 上次时间、最新时间
  let lastCode, nextCode; // 上次按键、最新按键
  document.onkeypress = (e) => {
    // 获取按键
    if (window.event) { // IE
      nextCode = e.keyCode
    } else if (e.which) { // Netscape/Firefox/Opera
      nextCode = e.which
    }
    // 如果触发了回车事件(扫码结束时间)
    if (nextCode === 13) {

      if (code.length < 3) return // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有

      codeFind(code) // 获取到扫码枪输入的内容，做别的操作

      code = ''
      lastCode = ''
      lastTime = ''
      return
    }
    nextTime = new Date().getTime() // 记录最新时间
    if (!lastTime && !lastCode) { // 如果上次时间和上次按键为空
      code += e.key // 执行叠加操作
    }
    // 如果有上次时间及上次按键
    if (lastCode && lastTime && nextTime - lastTime > 30) { // 当扫码前有keypress事件时,防止首字缺失
      code = e.key
    } else if (lastCode && lastTime) {
      code += e.key
    }
    lastCode = nextCode
    lastTime = nextTime
  }
}
const codeFind = (code) => {
  if (code.length===13)
    if (store.getLocalStorage(code)==null){
      addGoods(code)
    }
    else
      onAddItem(store.getLocalStorage(code))

}
const getTotalAndNum = () => {
  let num=0
  let total=0.0
  for (let i in curTableData.value){
    num+=1
    total+=curTableData.value[i].num*curTableData.value[i].cost
  }
  return{
    num,
    total
  }
}
const addGoodsNum = () => {
  if(radio.value==="扫码入库"){
    if (curTableData.value.length===0){
      ElMessage({
        message: '列表为空',
        type: 'warning',
      })
    }else {
      request.post("/goods/update/addGoodsNum",curTableData.value).then(res=>{
        ElMessage({
          message: '入库成功',
          type: 'success',
        })
        delMultipleSelectionScan(true)
        request.get("/goods/get/goodsInfo/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
          store.goodsStoreInfoList=res.data
          store.warnInventory=store.goodsStoreInfoList.filter((p)=>{
            return p.state===1
          })
        })
      })
    }
  }else {
    if (multipleSelection.value.length===0){
      ElMessage({
        message: '请先选中入库商品',
        type: 'warning',
      })
    }else {
      request.post("/goods/update/addGoodsNum",multipleSelection.value).then(res=>{
        ElMessage({
          message: '入库成功',
          type: 'success',
        })
        delMultipleSelectionScan(true)
        request.get("/goods/get/goodsInfo/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
          store.goodsStoreInfoList=res.data
          store.warnInventory=store.goodsStoreInfoList.filter((p)=>{
            return p.state===1
          })
        })
      })
    }
  }

}

watch(curTableData, (n, o) => {
  if (radio.value==="进货单"){
    goodsPurchase.value.orderDetailObject=curTableData.value
    request.post("/goods/update/goodsPurchase",goodsPurchase.value)
  }
}, {deep: true})

const addGoods = (code) => {
  goodsStore.code=code
  showAddNew.value=true
}
const goodsStore=reactive({
  code:"",
  goodsName:"",
  storeId:store.getLocalCurrentStoreMain().storeId,
  inventory:0,
  cost:0.0,
  price:0.0,
  warn:3
})
let addGoodsShow=ref(false)
const dom = ref()
const validateCode = (rule, value) => {
  if (value.length !== 13)
    return Promise.reject("请输入正确的13位条形码")
  else
    return Promise.resolve()

}
const validatePrice = (rule, value) => {
  if (value<=0)
    return Promise.reject("价格必须大于0")
  else
    return Promise.resolve()

}
const rules = reactive({
  code:[{validator: validateCode, trigger: 'change',required:true}],
  price:[{validator: validatePrice, trigger: 'change',required:true}]
})

const getSuggestedPrice = () => {
  if (goodsStore.code.length!==13){
    ElMessage({
      message: "请输入正确的商品条码",
      type: 'warning',
    })
  }else {
    request.get("/goods/get/suggestedPrice/"+goodsStore.code).then(res=>{
      if (res.data!==null)
        goodsStore.price=res.data
      else
        ElMessage({
          message: "没有此商品的建议价",
          type: 'warning',
        })
    })
  }
}
const submit = (dom) => {
  dom.validate((isTrue) => {
    if (isTrue) {
      request.post("/goods/add/goodsStore", [goodsStore]).then(response => {
        if (response.code === 200) {
          showAddNew.value=false
          ElMessage({
            message: "已新增商品",
            type: 'success',
          })
          request.get("/goods/get/goodsCodeList/"+store.getLocalCurrentStoreMain().storeId).then(res1=>{
            for (let i in res1.data){
              localStorage.removeItem(res1.data[i])
            }
            request.get("/goods/get/goodsInfo/"+store.getLocalCurrentStoreMain().storeId).then(res2=>{
              for (let i in res2.data){
                store.setLocalStorage(res2.data[i].code,res2.data[i])
              }
              store.resetStoreGoodsInfo()
              console.log("resetLocalGoodsInfo done")
              store.goodsStoreInfoList=[]
              for (let i in res1.data){
                store.goodsStoreInfoList.push(store.getLocalStorage(res1.data[i]))
              }
            })
          })
        } else {
          console.log(response)
          ElMessage({
            message: response.message,
            type:'error'
          })
        }
      })
    } else {
      console.log("格式有误")
    }
  })
}
</script>

<style scoped>

</style>